const express = require('express');
const http = require('http');
const socketIo = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketIo(server);

// 设置静态文件目录
app.use(express.static(__dirname));

// 监听连接事件
let onlineUsers = 0;

io.on('connection', (socket) => {
    onlineUsers++;
    io.emit('usersUpdate', onlineUsers);
    console.log('新用户连接，当前在线人数:', onlineUsers);

    // 监听用户加入事件
    socket.on('join', (username) => {
        socket.username = username;
        io.emit('system', `${username} 加入了聊天室`);
    });

    // 监听消息事件
    socket.on('message', (message) => {
        io.emit('message', {
            username: socket.username || '匿名用户',
            text: message,
            type: 'other'
        });
    });

    // 监听断开连接事件
    socket.on('disconnect', () => {
        onlineUsers--;
        io.emit('usersUpdate', onlineUsers);
        if (socket.username) {
            io.emit('system', `${socket.username} 离开了聊天室`);
        }
        console.log('用户断开连接，当前在线人数:', onlineUsers);
    });
});

// 启动服务器
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
    console.log('server is running at http://localhost:3000');
});
    